import 'package:core_package/core_package.dart';
import 'package:core_package/ui/widget/my_asset_image.dart';
import 'package:core_package/ui/widget/show_title_input_list_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_unionad/model/app_device_list_model.dart';
import 'package:flutter_app_unionad/request/workbench_request.dart';
import 'package:flutter_app_unionad/ui/basice/my_button.dart';
import 'package:flutter_app_unionad/ui/basice/title_alert_widget.dart';
import 'package:flutter_app_unionad/ui/my_facility/recharge_order_page.dart';
import 'package:flutter_app_unionad/ui/promotion/widget/promotion_input_widget.dart';
import 'package:flutter_app_unionad/ui/user_center/user_center_item0_page.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import '../work_activate_page.dart';

class WorkSearchWidget extends StatefulWidget {
  @override
  _WorkSearchWidgetState createState() => _WorkSearchWidgetState();
}

class _WorkSearchWidgetState extends State<WorkSearchWidget> {
  List<AppDeviceListModel>? dataSource;
  int page = 0;
  EasyRefreshController? _controller;
  String? name;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = EasyRefreshController();
    getData();
  }

  void getData() {
    page = 1;
    WorkBenchRequest.getAppDeviceList(
      pageNum: page,
      keyword: name,
    ).then((value) {
      if (value != null) {
        if (dataSource == null) dataSource = [];
        dataSource?.clear();
        dataSource?.addAll(value);
      }
      if (mounted) setState(() {});
    });
  }

  void getMoreData() {
    page++;
    WorkBenchRequest.getAppDeviceList(
      pageNum: page,
      keyword: name,
    ).then((value) {
      if (value != null) {
        if (dataSource == null) dataSource = [];
        dataSource?.addAll(value);
      }
      if (dataSource != null && dataSource!.length < 20) {
        _controller?.finishLoadCallBack?.call();
      } else {
        _controller?.resetLoadStateCallBack?.call();
      }
      if (mounted) setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        buildTopWidget(),
        SizedBox(height: 10.px),
        Expanded(child: buildContent()),
      ],
    );
  }

  Widget buildContent() {
    if (dataSource == null) {
      return ProgressDialog.showFirstLoading();
    }
    if (dataSource!.length == 0) {
      return Container(
        color: MyColors.color_246_244_239,
        child: EmptyWidget(),
      );
    }
    return Container(
      color: MyColors.color_246_244_239,
      child: EasyRefresh(
        header: RefreshBasics.header,
        footer: RefreshBasics.footer,
        controller: _controller,
        onRefresh: () async {
          getData();
        },
        onLoad: () async {
          getMoreData();
        },
        child: ListView.builder(
          padding: EdgeInsets.zero,
          itemCount: dataSource!.length,
          itemBuilder: (ctx, index) {
            return buildListItem(index);
          },
        ),
      ),
    );
  }

  Widget buildListItem(int index) {
    AppDeviceListModel model = dataSource![index];
    return Container(
      margin: EdgeInsets.only(bottom: 10.px),
      padding: EdgeInsets.only(
        left: 30.px,
        top: 30.px,
        bottom: 30.px,
        right: 20.px,
      ),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.white,
      ),
      child: Column(
        children: [
          buildRowItem('take_address', '${model.devid},${model.contractTel}\n${model.devAddress}', Size(11, 13)),
          MySizeBox(height: 5),
          buildRowItem('take_info', '剩余天数\n${model.remainDays}', Size(11, 9)),
          MySizeBox(height: 5),
          Row(
            children: [
              Expanded(child: SizedBox()),
              buildButton(
                title: '激活',
                onTop: () {
                  ShowCenterAlertDialog.showAlert(context, height: 170.px, builder: (ctx) {
                    return TitleAlertWidget(
                      title: "激活",
                      subTitle: "确定要激活吗?",
                      actions: ["取消", "确定"],
                      actionsColors: [Colors.black12, MyColors.color_245_174_41],
                      actionsTitleColors: [Colors.white, Colors.white],
                      onTap: (index) {
                        if (index == 0) {
                          Navigator.pop(context, false);
                        } else {
                          Navigator.pop(context, true);
                        }
                      },
                    );
                  }).then(
                    (value) {
                      if (value != null && value) {
                        ProgressDialog.showProgress(context);
                        WorkBenchRequest.appInitDeviceOnly(devSn: model.devSn).then((value) {
                          ProgressDialog.dismiss(context);
                        });
                      }
                    },
                  );
                  // ShowCenterAlertDialog.showAlert(context, builder: (ctx) {
                  //   return PromotionInputWidget(
                  //     title: '请输入设备号',
                  //     buttonTitle: '激活',
                  //     onTap: (value) {
                  //       if (value.stringIsEmpty) {
                  //         ShowToastWidget.showToast(msg: '请输入设备号');
                  //         return;
                  //       }
                  //       ProgressDialog.showProgress(context);
                  //       WorkBenchRequest.appInitDeviceOnly(devSn: value).then((value) {
                  //         ProgressDialog.dismiss(context);
                  //         if (value) Navigator.pop(context);
                  //       });
                  //     },
                  //   );
                  // }, width: 335.px, height: 210.px);
                },
              ),
              MySizeBox(width: 5),
              buildButton(
                title: '启动',
                onTop: () {
                  ShowCenterAlertDialog.showAlert(context, height: 170.px, builder: (ctx) {
                    return TitleAlertWidget(
                      title: "启动",
                      subTitle: "确定要启动吗?",
                      actions: ["取消", "确定"],
                      actionsColors: [Colors.black12, MyColors.color_245_174_41],
                      actionsTitleColors: [Colors.white, Colors.white],
                      onTap: (index) {
                        if (index == 0) {
                          Navigator.pop(context, false);
                        } else {
                          Navigator.pop(context, true);
                        }
                      },
                    );
                  }).then(
                    (value) {
                      if (value != null && value) {
                        ProgressDialog.showProgress(context);
                        WorkBenchRequest.appPayCalibration(devSn: model.devSn).then((value) {
                          ProgressDialog.dismiss(context);
                        });
                      }
                    },
                  );
                  //
                  // ShowCenterAlertDialog.showAlert(context, builder: (ctx) {
                  //   return PromotionInputWidget(
                  //     title: '请输入设备号',
                  //     buttonTitle: '启动',
                  //     onTap: (value) {
                  //       if (value.stringIsEmpty) {
                  //         ShowToastWidget.showToast(msg: '请输入设备号');
                  //         return;
                  //       }
                  //       ProgressDialog.showProgress(context);
                  //       WorkBenchRequest.appPayCalibration(devSn: value).then((value) {
                  //         ProgressDialog.dismiss(context);
                  //         if (value) Navigator.pop(context);
                  //       });
                  //     },
                  //   );
                  // }, width: 335.px, height: 210.px);
                },
              ),
              // MySizeBox(width: 5),
              // buildButton(
              //   title: '充值记录',
              //   onTop: () {
              //     //
              //     NavigatorUtil.push(context, RechargeOrderPage.routeName, arguments: {'id': da});
              //   },
              // ),
              // MySizeBox(width: 5),
              // buildButton(
              //   title: '换芯记录',
              //   onTop: () {
              //     //
              //     NavigatorUtil.push(
              //       context,
              //       UserCenterItem0Page.routeName,
              //       arguments: {'id': 124},
              //     );
              //   },
              // ),
            ],
          )
        ],
      ),
    );
  }

  Widget buildRowItem(String icon, String title, Size size) {
    return Row(
      children: [
        MyAssetImage(
          icon,
          width: size.width.px,
          height: size.height.px,
        ),
        MySizeBox(width: 15),
        Expanded(
          child: Text(
            title,
            style: TextStyle(
              color: MyColors.color_27_27_27,
              fontSize: MyFont.font12,
            ),
          ),
        )
      ],
    );
  }

  Widget buildButton({String? title, Function()? onTop}) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: onTop,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 15.px, vertical: 5.px),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5.px),
          border: Border.all(color: MyColors.color_27_27_27, width: 0.5),
        ),
        alignment: Alignment.center,
        child: Text(
          title ?? '',
          style: TextStyle(color: MyColors.color_27_27_27, fontSize: MyFont.font11),
        ),
      ),
    );
  }

  Widget buildTopWidget() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.px, vertical: 20.px),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5),
      ),
      child: Row(
        children: [
          Expanded(child: buildSearchWidget()),
          MySizeBox(width: 10),
          MyButton(
            title: "查询",
            width: 90.px,
            height: 33.px,
            onTap: () {
              if (name == null || name!.stringIsEmpty) return;
              getData();
            },
          ),
        ],
      ),
    );
  }

  Widget buildSearchWidget() {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: MyColors.color_27_27_27, width: 0.5),
        borderRadius: BorderRadius.circular(5),
      ),
      child: ShowTitleInputListWidget(
        padding: EdgeInsets.zero,
        textFieldHeight: 33.px,
        textAlign: TextAlign.left,
        placeholder: "搜索关键词",
        inputTextTapChange: (value) => name = value,
        placeholderStyle: TextStyle(color: MyColors.formHex("#CDCDCDFF"), fontSize: MyFont.font12),
        inputStyle: TextStyle(color: MyColors.color_27_27_27, fontSize: MyFont.font12),
        titleWidget: Container(
          width: 40.px,
          height: 33.px,
          child: Center(
            child: MyAssetImage(
              "take_search",
              width: 12.px,
              height: 12.px,
            ),
          ),
        ),
      ),
    );
  }
}
